import {
  Controller,
  Get,
  Query,
  Param,
  HttpCode,
  HttpStatus,
  UseGuards,
  ParseIntPipe,
  DefaultValuePipe,
  BadRequestException
} from '@nestjs/common';
import { CopilotRequestLoggerService } from '../services/copilot-request-logger.service';
import { FieldDiffTrackerService } from '../services/field-diff-tracker.service';
import { RequestStatus } from '../../database/entities/copilot-types';
// JWT auth guard is not available in this project
// import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';

export interface LogQueryDto {
  page?: number;
  pageSize?: number;
  status?: RequestStatus;
  startTime?: string;
  endTime?: string;
  userId?: string;
  search?: string;
}

export interface StatisticsQueryDto {
  startTime?: string;
  endTime?: string;
  period?: 'hour' | 'day' | 'week' | 'month';
}

@Controller('v1/copilot/logs')
// @UseGuards(JwtAuthGuard)
export class CopilotLogsController {
  constructor(
    private readonly loggerService: CopilotRequestLoggerService,
    private readonly diffTrackerService: FieldDiffTrackerService
  ) {}

  /**
   * 获取请求日志列表
   */
  @Get()
  @HttpCode(HttpStatus.OK)
  async getRequestLogs(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('pageSize', new DefaultValuePipe(20), ParseIntPipe) pageSize: number,
    @Query('status') status?: RequestStatus,
    @Query('startTime') startTime?: string,
    @Query('endTime') endTime?: string,
    @Query('userId') userId?: string,
    @Query('search') search?: string
  ) {
    try {
      // 验证分页参数
      if (page < 1 || pageSize < 1 || pageSize > 100) {
        throw new BadRequestException('无效的分页参数');
      }

      // 解析时间参数
      const parseDate = (dateStr?: string): Date | undefined => {
        if (!dateStr) return undefined;
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
          throw new BadRequestException(`无效的时间格式: ${dateStr}`);
        }
        return date;
      };

      const options = {
        page,
        pageSize,
        status,
        startTime: parseDate(startTime),
        endTime: parseDate(endTime),
        userId
      };

      const result = await this.loggerService.getRequestLogs(options);

      // 添加搜索过滤（简单的内存搜索，生产环境应该在数据库层面实现）
      if (search) {
        const searchLower = search.toLowerCase();
        result.data = result.data.filter(log =>
          log.requestId.toLowerCase().includes(searchLower) ||
          log.modelName?.toLowerCase().includes(searchLower) ||
          log.errorMessage?.toLowerCase().includes(searchLower) ||
          log.userId?.toLowerCase().includes(searchLower)
        );
        result.total = result.data.length;
      }

      return {
        success: true,
        data: {
          ...result,
          // 为每个日志记录添加摘要信息
          data: result.data.map(log => ({
            ...log,
            summary: {
              isCompleted: log.isCompleted(),
              performance: log.getPerformanceSummary(),
              error: log.getErrorSummary(),
              timeline: log.getTimeline()
            }
          }))
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '获取日志列表失败',
        data: null
      };
    }
  }

  /**
   * 获取单个请求的详细信息
   */
  @Get(':requestId')
  @HttpCode(HttpStatus.OK)
  async getRequestLogDetail(@Param('requestId') requestId: string) {
    try {
      if (!requestId || requestId.length !== 36) {
        throw new BadRequestException('无效的请求ID格式');
      }

      const requestLog = await this.loggerService.getRequestLogDetail(requestId);
      
      if (!requestLog) {
        return {
          success: false,
          message: '请求日志不存在',
          data: null
        };
      }

      return {
        success: true,
        data: {
          ...requestLog,
          summary: {
            isCompleted: requestLog.isCompleted(),
            performance: requestLog.getPerformanceSummary(),
            error: requestLog.getErrorSummary(),
            timeline: requestLog.getTimeline()
          },
          fieldMappingsCount: requestLog.fieldMappings?.length || 0
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '获取请求详情失败',
        data: null
      };
    }
  }

  /**
   * 获取字段映射变化记录
   */
  @Get(':requestId/field-mappings')
  @HttpCode(HttpStatus.OK)
  async getFieldMappings(
    @Param('requestId') requestId: string,
    @Query('phase') phase?: string
  ) {
    try {
      if (!requestId || requestId.length !== 36) {
        throw new BadRequestException('无效的请求ID格式');
      }

      const fieldMappings = await this.loggerService.getFieldMappings(requestId);

      // 按阶段分组
      const groupedMappings = fieldMappings.reduce((groups, mapping) => {
        const key = `${mapping.fromPhase}_to_${mapping.toPhase}`;
        if (!groups[key]) {
          groups[key] = [];
        }
        groups[key].push({
          ...mapping,
          description: mapping.getChangeDescription(),
          severity: mapping.getChangeSeverity(),
          isCritical: mapping.isCriticalChange()
        });
        return groups;
      }, {} as Record<string, any[]>);

      // 生成变化摘要
      const changeSummary = this.diffTrackerService.generateChangeSummary(
        fieldMappings.map(mapping => ({
          fieldPath: mapping.fieldPath,
          mappingType: mapping.mappingType,
          fromValue: mapping.fromValue,
          toValue: mapping.toValue,
          fromFieldName: mapping.fromFieldName,
          toFieldName: mapping.toFieldName
        }))
      );

      // 分析转换模式
      const transformationPattern = this.diffTrackerService.analyzeTransformationPattern(
        fieldMappings.map(mapping => ({
          fieldPath: mapping.fieldPath,
          mappingType: mapping.mappingType,
          fromValue: mapping.fromValue,
          toValue: mapping.toValue,
          fromFieldName: mapping.fromFieldName,
          toFieldName: mapping.toFieldName
        }))
      );

      return {
        success: true,
        data: {
          groupedMappings,
          changeSummary,
          transformationPattern,
          totalMappings: fieldMappings.length
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '获取字段映射失败',
        data: null
      };
    }
  }

  /**
   * 获取统计信息
   */
  @Get('statistics/overview')
  @HttpCode(HttpStatus.OK)
  async getStatistics(
    @Query('startTime') startTime?: string,
    @Query('endTime') endTime?: string,
    @Query('period') period: 'hour' | 'day' | 'week' | 'month' = 'day'
  ) {
    try {
      // 解析时间范围
      let timeRange: { start: Date; end: Date } | undefined;
      
      if (startTime && endTime) {
        const start = new Date(startTime);
        const end = new Date(endTime);
        
        if (isNaN(start.getTime()) || isNaN(end.getTime())) {
          throw new BadRequestException('无效的时间格式');
        }
        
        if (start >= end) {
          throw new BadRequestException('开始时间必须小于结束时间');
        }
        
        timeRange = { start, end };
      } else {
        // 默认获取最近7天的数据
        const end = new Date();
        const start = new Date();
        start.setDate(end.getDate() - 7);
        timeRange = { start, end };
      }

      const statistics = await this.loggerService.getStatistics(timeRange);

      // 计算额外的统计指标
      const successRate = statistics.totalRequests > 0 
        ? Math.round((statistics.successRequests / statistics.totalRequests) * 100) 
        : 0;

      const errorRate = statistics.totalRequests > 0 
        ? Math.round((statistics.errorRequests / statistics.totalRequests) * 100) 
        : 0;

      return {
        success: true,
        data: {
          ...statistics,
          successRate,
          errorRate,
          timeRange: {
            start: timeRange.start.toISOString(),
            end: timeRange.end.toISOString(),
            period
          }
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '获取统计信息失败',
        data: null
      };
    }
  }

  /**
   * 获取请求性能分析
   */
  @Get('analytics/performance')
  @HttpCode(HttpStatus.OK)
  async getPerformanceAnalytics(
    @Query('startTime') startTime?: string,
    @Query('endTime') endTime?: string,
    @Query('interval', new DefaultValuePipe('hour')) interval: 'minute' | 'hour' | 'day' = 'hour'
  ) {
    try {
      // 这里应该实现更详细的性能分析查询
      // 由于时间关系，先返回基础统计信息
      
      let timeRange: { start: Date; end: Date } | undefined;
      if (startTime && endTime) {
        timeRange = {
          start: new Date(startTime),
          end: new Date(endTime)
        };
      }

      const statistics = await this.loggerService.getStatistics(timeRange);

      return {
        success: true,
        data: {
          performanceMetrics: {
            averageResponseTime: statistics.averageResponseTime,
            totalRequests: statistics.totalRequests,
            successRate: statistics.totalRequests > 0 
              ? Math.round((statistics.successRequests / statistics.totalRequests) * 100) 
              : 0
          },
          // TODO: 实现按时间间隔的性能趋势分析
          trends: [],
          bottlenecks: statistics.topErrors.slice(0, 3)
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '获取性能分析失败',
        data: null
      };
    }
  }

  /**
   * 获取字段转换分析
   */
  @Get('analytics/field-transformations')
  @HttpCode(HttpStatus.OK)
  async getFieldTransformationAnalytics(
    @Query('startTime') startTime?: string,
    @Query('endTime') endTime?: string
  ) {
    try {
      // 这里应该实现字段转换的统计分析
      // 由于时间关系，先返回基础信息
      
      return {
        success: true,
        data: {
          commonTransformations: [
            { field: 'messages', transformations: 'content格式转换', frequency: 95 },
            { field: 'model', transformations: '模型名映射', frequency: 100 },
            { field: 'max_tokens', transformations: '参数名转换', frequency: 80 },
            { field: 'temperature', transformations: '数值范围调整', frequency: 60 }
          ],
          transformationPatterns: {
            'anthropic_to_copilot': {
              fieldAdditions: 15,
              fieldRemovals: 8,
              valueTransformations: 25,
              structureChanges: 5
            }
          },
          // TODO: 实现更详细的转换分析
          criticalTransformations: []
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '获取字段转换分析失败',
        data: null
      };
    }
  }

  /**
   * 导出日志数据
   */
  @Get('export/:format')
  @HttpCode(HttpStatus.OK)
  async exportLogs(
    @Param('format') format: 'json' | 'csv',
    @Query('startTime') startTime?: string,
    @Query('endTime') endTime?: string,
    @Query('requestIds') requestIds?: string
  ) {
    try {
      // 验证导出格式
      if (!['json', 'csv'].includes(format)) {
        throw new BadRequestException('不支持的导出格式');
      }

      // TODO: 实现实际的导出逻辑
      // 这里只是返回一个示例响应
      
      return {
        success: true,
        message: `${format.toUpperCase()} 导出功能开发中`,
        data: {
          downloadUrl: null,
          estimatedTime: '预计需要 1-2 分钟',
          format
        }
      };
    } catch (error) {
      return {
        success: false,
        message: error.message || '导出失败',
        data: null
      };
    }
  }
}